package com.tarena.lbs.activity.rpc;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tarena.lbs.activity.api.ActivityApi;
import com.tarena.lbs.activity.api.pojo.ActivityDto;
import com.tarena.lbs.activity.dao.repository.ActivityRepository;
import com.tarena.lbs.activity.pojo.po.ActivityPO;
import com.tarena.lbs.activity.pojo.vo.ActivityVO;
import com.tarena.lbs.activity.service.ActivityService;
import com.tarena.lbs.user.api.UserApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
@DubboService
public class ActivityApiImpl implements ActivityApi {

    @Autowired
    private ActivityService activityService;
    @Autowired
    private ActivityRepository activityRepository;
    @DubboReference
    private UserApi userApi;

    @Override
    public Boolean activityVisible(Integer userId, Integer activityId) {
        log.debug("活动检查Api,入参:userId={},activityId={}", userId, activityId);
        ActivityPO activityPO = activityRepository.selectActivityById(activityId);
        if (activityPO == null) {
            log.error("活动不存在,activityId={}", activityId);
            return false;
        }
        String targetCustomer = activityPO.getTargetCustomer();
        if (targetCustomer == null || targetCustomer.isEmpty()) {
            log.debug("活动目标人群为空,activityId={}", activityId);
            return true;
        }
        List<String> targetCustomerList = Arrays.asList(targetCustomer.split(","));
        List<Integer> userGroupIds = userApi.getUserGroupIds(userId, activityPO.getBusinessId());
        if (CollectionUtils.isEmpty(userGroupIds)) {
            return false;
        }
        for (Integer userGroupId : userGroupIds) {
            if (targetCustomerList.contains(userGroupId.toString())) {
                return true;
            }
        }
        log.error("用户{}未满足活动{}的目标人群", userId, activityId);
        return false;
    }

    @Override
    public ActivityDto getActivityById(Integer activityId) {
        ActivityDto activityDto = null;
        ActivityVO activityVO = activityService.activityDetail(activityId);
        if (activityVO != null) {
            activityDto = new ActivityDto();
            BeanUtils.copyProperties(activityVO,activityDto);
        }
        return activityDto;
    }
}
